import { resumeUploadManager, UploadTask } from './resumeUpload'
import { validateFileType, validateFileSize } from './ossConfig'

// 上传进度回调类型
export type ResumeUploadProgressCallback = (task: UploadTask) => void

// 上传结果类型
export interface ResumeUploadResult {
  success: boolean
  url?: string
  error?: string
  taskId?: string
  fileName?: string
  fileSize?: number
  uploadTime?: number
}

// 断点续传上传函数
export const uploadWithResume = async (
  file: File,
  onProgress?: ResumeUploadProgressCallback,
  objectKey?: string
): Promise<ResumeUploadResult> => {
  const startTime = Date.now()

  try {
    // 验证文件类型
    if (!validateFileType(file)) {
      return {
        success: false,
        error: '不支持的文件类型，请上传图片文件',
        fileSize: file.size
      }
    }

    // 验证文件大小
    if (!validateFileSize(file)) {
      return {
        success: false,
        error: `文件大小不能超过 ${100}MB`, // 从OSS_CONFIG获取
        fileSize: file.size
      }
    }

    // 创建上传任务
    const task = resumeUploadManager.createUploadTask(file, objectKey)
    
    // 设置进度回调
    const progressCallback = onProgress ? (updatedTask: UploadTask) => {
      onProgress(updatedTask)
    } : undefined

    // 开始上传
    const result = await resumeUploadManager.startUpload(task.id, file, progressCallback)

    return {
      success: result.success,
      url: result.url,
      error: result.error,
      taskId: task.id,
      fileName: task.fileName,
      fileSize: task.fileSize,
      uploadTime: Date.now() - startTime
    }

  } catch (error) {
    console.error('断点续传上传失败:', error)
    return {
      success: false,
      error: error instanceof Error ? error.message : '上传失败',
      fileSize: file.size,
      uploadTime: Date.now() - startTime
    }
  }
}

// 暂停上传
export const pauseUpload = async (taskId: string): Promise<boolean> => {
  return await resumeUploadManager.pauseUpload(taskId)
}

// 恢复上传
export const resumeUpload = async (
  taskId: string,
  file: File,
  onProgress?: ResumeUploadProgressCallback
): Promise<ResumeUploadResult> => {
  const startTime = Date.now()
  const task = resumeUploadManager.getTask(taskId)
  
  if (!task) {
    return {
      success: false,
      error: '任务不存在或已完成'
    }
  }

  try {
    // 设置进度回调
    const progressCallback = onProgress ? (updatedTask: UploadTask) => {
      onProgress(updatedTask)
    } : undefined

    // 恢复上传
    const result = await resumeUploadManager.startUpload(taskId, file, progressCallback)

    return {
      success: result.success,
      url: result.url,
      error: result.error,
      taskId: task.id,
      fileName: task.fileName,
      fileSize: task.fileSize,
      uploadTime: Date.now() - startTime
    }

  } catch (error) {
    console.error('恢复上传失败:', error)
    return {
      success: false,
      error: error instanceof Error ? error.message : '恢复上传失败',
      fileSize: task.fileSize,
      uploadTime: Date.now() - startTime
    }
  }
}

// 取消上传
export const cancelUpload = async (taskId: string): Promise<boolean> => {
  return await resumeUploadManager.cancelUpload(taskId)
}

// 获取任务信息
export const getUploadTask = (taskId: string): UploadTask | undefined => {
  return resumeUploadManager.getTask(taskId)
}

// 获取所有任务
export const getAllUploadTasks = (): UploadTask[] => {
  return resumeUploadManager.getAllTasks()
}

// 清理已完成的任务
export const clearCompletedTasks = (): void => {
  resumeUploadManager.clearCompletedTasks()
}

// 清理所有任务
export const clearAllTasks = (): void => {
  resumeUploadManager.clearAllTasks()
}

// 批量上传文件（支持断点续传）
export const uploadMultipleFilesWithResume = async (
  files: File[],
  onProgress?: (fileIndex: number, task: UploadTask) => void
): Promise<ResumeUploadResult[]> => {
  const results: ResumeUploadResult[] = []
  
  for (let i = 0; i < files.length; i++) {
    const file = files[i]
    const result = await uploadWithResume(file, (task) => {
      if (onProgress) {
        onProgress(i, task)
      }
    })
    results.push(result)
  }
  
  return results
}

// 检查是否有未完成的上传任务
export const hasUnfinishedTasks = (): boolean => {
  const tasks = resumeUploadManager.getAllTasks()
  return tasks.some(task => task.status === 'paused' || task.status === 'failed')
}

// 获取未完成的任务
export const getUnfinishedTasks = (): UploadTask[] => {
  const tasks = resumeUploadManager.getAllTasks()
  return tasks.filter(task => task.status === 'paused' || task.status === 'failed')
}

// 重试失败的任务
export const retryFailedUpload = async (
  taskId: string,
  file: File,
  onProgress?: ResumeUploadProgressCallback
): Promise<ResumeUploadResult> => {
  const task = resumeUploadManager.getTask(taskId)
  
  if (!task) {
    return {
      success: false,
      error: '任务不存在'
    }
  }

  if (task.status !== 'failed') {
    return {
      success: false,
      error: '任务状态不是失败状态，无法重试'
    }
  }

  // 重置任务状态
  task.status = 'pending'
  task.error = undefined
  task.lastUpdateTime = Date.now()
  
  // 重新开始上传
  return await resumeUpload(taskId, file, onProgress)
}
